import { ArgumentsHost, ExceptionFilter, HttpException, HttpStatus } from "@nestjs/common";
import {Response} from 'express'
export class GlobalHttpExceptionFilter implements ExceptionFilter{
    catch(exception: any, host: ArgumentsHost) {
        const ctx = host.switchToHttp()
        const response = ctx.getResponse<Response>()
        if (response.headersSent) {
            return
        }
        if (exception instanceof HttpException) {
            if (typeof exception.getResponse() === 'string') {

                const status = exception.getStatus()
                response.status(status).json({
                    statusCode: status,
                    message: exception.getResponse()
                })
            } else {
                response.status(exception.getStatus()).json(exception.getResponse())
            }
            
        } else {
            return response.status(500).json({
                statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
                message: 'internal server error'
            })
        }
    }
}